const router = require('koa-router')()
const JWT = require('jsonwebtoken')
const key = 'yugytryetsfe'
const userList = [{
  "id": "1",
  "username": "admin",
  "password": "admin",
  "nickname": "管理员",
  "role": 'admin',
  "avatar": "https://robohash.org/123?set=set5",
  "sign": "幽梦在那个管理人员"
}, {
  "id": "2",
  "username": "zhangsan",
  "password": "zhangsan",
  "nickname": "一个有梦想的印度阿三",
  "role": 'user',
  "avatar": "https://robohash.org/123?set=set5",
  "sign": "立志当一个爹二代"
}]

router.post('/login', ctx => {
  const { username, password } = ctx.request.body;
  const user = userList.find(v => v.username === username && v.password === password);
  if (user) {
    ctx.body = {
      code: 200,
      message: '登录成功，欢迎' + user.nickname,
      data: {
        userInfo: user,
        token: JWT.sign(user, key, {
          // 有效时间 单位 s
          expiresIn: 60 * 60
        })
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: '账户密码错误， 请重新登录'
    }
  }
})

module.exports = router
